//
//  AppDelegate+CheckPermissions.m
//  ZZmetro
//
//  Created by 一介布衣 on 2020/6/4.
//  Copyright © 2020 一介布衣. All rights reserved.
//

#import "AppDelegate+CheckPermissions.h"
#import <AFNetworkReachabilityManager.h>
#import <Foundation/Foundation.h>


@implementation AppDelegate (CheckPermissions)
#pragma mark - get/set
- (void)setOpenAppFromBackground:(BOOL)openAppFromBackground
{
    //objc_setAssociatedObject(self, @selector(openAppFromBackground), @(openAppFromBackground), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)openAppFromBackground
{
    //NSNumber *number = objc_getAssociatedObject(self, @selector(openAppFromBackground));
    
    //return [number boolValue];
    
    return NO;
}

- (void)setNetworkAlertView:(UIAlertView *)networkAlertView
{
    //objc_setAssociatedObject(self, @selector(networkAlertView), networkAlertView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIAlertView *)networkAlertView
{
    //return objc_getAssociatedObject(self, @selector(networkAlertView));
    return nil;
}

- (void)setMessageAlertView:(UIAlertView *)messageAlertView
{
    //objc_setAssociatedObject(self, @selector(messageAlertView), messageAlertView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIAlertView *)messageAlertView
{
    //return objc_getAssociatedObject(self, @selector(messageAlertView));
    return nil;
}

- (void)setGpsAlertView:(UIAlertView *)gpsAlertView
{
    //objc_setAssociatedObject(self, @selector(gpsAlertView), gpsAlertView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIAlertView *)gpsAlertView
{
    //return objc_getAssociatedObject(self, @selector(gpsAlertView));
    return nil;
}

- (void)setDidBecomeActive:(BOOL)didBecomeActive
{
    //objc_setAssociatedObject(self, @selector(didBecomeActive), @(didBecomeActive), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)didBecomeActive
{
    //NSNumber *number = objc_getAssociatedObject(self, @selector(didBecomeActive));
    
    //return [number boolValue];
    
    return NO;
}

- (void)setBackgroundTaskId:(UIBackgroundTaskIdentifier)backgroundTaskId
{
    //objc_setAssociatedObject(self, @selector(backgroundTaskId), @(backgroundTaskId), OBJC_ASSOCIATION_ASSIGN);
}

- (UIBackgroundTaskIdentifier)backgroundTaskId
{
    //NSNumber *number = objc_getAssociatedObject(self, @selector(backgroundTaskId));
    
    //return [number boolValue];
    return nil;
}

- (void)setCheckFlag:(NSUInteger)checkFlag
{
    //objc_setAssociatedObject(self, @selector(checkFlag), @(checkFlag), OBJC_ASSOCIATION_ASSIGN);
}

- (NSUInteger)checkFlag
{
    //NSNumber *number = objc_getAssociatedObject(self, @selector(checkFlag));
    
    //return [number unsignedIntegerValue];
    return 0;
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    self.checkFlag --;
    if (self.messageAlertView == alertView)
    {
        self.messageAlertView = nil;
    }
    
    if (self.gpsAlertView == alertView)
    {
        self.gpsAlertView = nil;
    }
    
    if (self.networkAlertView == alertView)
    {
        self.networkAlertView = nil;
    }
    
    switch (buttonIndex)
    {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - 提示框
- (UIAlertView *)showAlertViewWithTitle:(NSString *)title message:(NSString *)message flag:(NSUInteger)flag
{
    self.checkFlag ++;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles:@"设置", nil];
    
    [alertView show];
    
    return alertView;
}

- (UIAlertController *)showAlertControllerWithTitle:(NSString *)title message:(NSString *)message flag:(NSUInteger)flag
{
    self.checkFlag ++;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    CommonWeakSelf;
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        CommonStrongSelf;
        strongSelf.checkFlag --;
    }];
    [alertController addAction:cancel];
    
    UIAlertAction *done = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        CommonStrongSelf;
        strongSelf.checkFlag --;
 
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [[UIApplication sharedApplication] openURL:url];
        }
    }];
    [alertController addAction:done];
    
    [self.window.rootViewController presentViewController:alertController animated:YES completion:NULL];
    
    return alertController;
}

#pragma mark - 网络检查
- (void)netWorkStatusListener
{
    CommonWeakSelf;
    
    [HttpRequestOperation startMonitoringWithResult:^(BOOL invalid) {
        CommonStrongSelf;
        if (!invalid)
        {
            [strongSelf showNetworkAlert];
        } else
        {
            if (self.networkAlertView)
            {
                [self.networkAlertView dismissWithClickedButtonIndex:0 animated:YES];
                self.networkAlertView = nil;
            }
        }
    }];
}

- (void)showNetworkAlert
{
    if (self.networkAlertView == nil)
    {
        NSString *title = @"无法访问网络";
        NSString *content = [NSString stringWithFormat:@"请检查您的网络设置,您可以\n1.在设备的”设置“-”Wi-Fi网络“设置面板中选择一个可用的Wi-Fi热点接入\n2.在设备的”设置“-”蜂窝移动网络“设置面板中启用蜂窝移动数据（确保允许“%@”应用访问网络)", [App name]];
        
        self.networkAlertView = [self showAlertViewWithTitle:title message:content flag:3];
    }
}

#pragma mark - 申请后台执行(申请的时间是可以进行网络通讯的)
- (void)requestBackgroundTask
{
    if (self.didBecomeActive)
    {
        return;
    }
    
    UIApplication *app = [UIApplication sharedApplication];
    
    if (self.backgroundTaskId)//该变量将作为后台任务的标识符
    {
        // 干掉重新再申请
        [app endBackgroundTask:self.backgroundTaskId];
    }
    
     CommonWeakSelf;
    self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
        //DLog(@"时间到了");
        CommonStrongSelf;
        // 申请时长到了
        [strongSelf requestBackgroundTask];
    }];
    
    if(self.backgroundTaskId == UIBackgroundTaskInvalid)
    {
        return;
    }
    
    //DLog(@"申请的后台任务时间为: %f",app.backgroundTimeRemaining);
    
    [Queue delay:120 task:^{
        if(self.didBecomeActive){
            return;
        }
        //TODO
        //[self requestBackgroundTask];
    }];
}

#pragma mark - public
- (void)applicationWillEnterForegroundWithCheckPermissions
{
    [HttpRequestOperation startMonitoringWithResult:^(BOOL invalid) {
        
    }];
    
    
    if (!self.openAppFromBackground)
    {
        self.openAppFromBackground = YES;
    }
    
    [self checkAllPermissions];
}

- (void)applicationDidEnterBackgroundWithCheckPermissions
{
    [self requestBackgroundTask];// 进入后台立刻出发一次通知，确保后台申请执行
}

- (void)applicationWillTerminateWithCheckPermissions
{
    
}

- (void)applicationWillResignActiveWithCheckPermissions
{
    self.didBecomeActive = NO;
}

- (void)applicationDidBecomeActiveWithCheckPermissions
{
    self.didBecomeActive = YES;
    
    if (!self.openAppFromBackground)
    {
        self.openAppFromBackground = YES;
        
         [self checkAllPermissions];
    }
}

- (void)checkAllPermissions
{
   
}
@end
